package com.gomtel.smartdevice.ui.activity;

import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.clj.fastble.data.BleDevice;
import com.gomtel.smartdevice.R;
import com.gomtel.smartdevice.api.BleManager;
import com.gomtel.smartdevice.api.MessageManager;
import com.gomtel.smartdevice.base.WatchAppBaseActivity;
import com.gomtel.smartdevice.bean.UserContent;
import com.gomtel.smartdevice.bt.ble.BLEDevice;
import com.gomtel.smartdevice.global.DataClass;
import com.gomtel.smartdevice.global.WatchApplication;
import com.gomtel.smartdevice.interfaces.OnConnectListener;
import com.gomtel.smartdevice.interfaces.OnFotaCallbackListener;
import com.gomtel.smartdevice.interfaces.OnScannerListener;
import com.gomtel.smartdevice.interfaces.Progress;
import com.gomtel.smartdevice.moudle.db.entity.AppConfigurationInfo;
import com.gomtel.smartdevice.moudle.db.entity.BdDataInfo;
import com.gomtel.smartdevice.moudle.db.entity.CaloryDataInfo;
import com.gomtel.smartdevice.moudle.db.entity.HeartRateDataInfo;
import com.gomtel.smartdevice.moudle.db.entity.PulseConditionBean;
import com.gomtel.smartdevice.moudle.event.CommonEvent;
import com.gomtel.smartdevice.moudle.event.EventCode;
import com.gomtel.smartdevice.moudle.rxtools.EventBusUtil;
import com.gomtel.smartdevice.net.NetUtils;
import com.gomtel.smartdevice.receiver.LocalBroadcastReceiver;
import com.gomtel.smartdevice.receiver.OnePixelReceiver;
import com.gomtel.smartdevice.ui.fragment.HomeFragment;
import com.gomtel.smartdevice.ui.fragment.PersonageFragment;
import com.gomtel.smartdevice.utils.CommonUtils;
import com.gomtel.smartdevice.utils.LogUtil;
import com.gomtel.smartdevice.widget.BlueToothClass;
import com.gomtel.smartdevice.widget.CalenderUtilsClass;
import com.gomtel.smartdevice.widget.Constants;
import com.gomtel.smartdevice.widget.LoginWidgetClass;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import me.yokeyword.fragmentation.SupportFragment;

/**
 * Created by Administrator on 2018/5/14 0014.
 */

public class HomeActivity extends WatchAppBaseActivity implements View.OnClickListener, RadioGroup.OnCheckedChangeListener, OnConnectListener {

    @BindView(R.id.group_view)
    RadioGroup group_view;
    private int showFragment = Constants.TYPE_LIFE;
    private int hideFragment = Constants.TYPE_LIFE;
    private HomeFragment homeFragment;
    private PersonageFragment personageFragment;
    private BlueToothClass blueToothClass;
    public static final int FILE_SELECT_CODE = 0;
    public static boolean isUnbind = false;
    private DataClass dataClass;
    private double exitTime = 0;
    private OnePixelReceiver onePixelReceiver;
    private LoginWidgetClass loginWidgetClass;
    private int responseHr;
    private LocalBroadcastReceiver localBroadcastReceiver;

    public Handler getHandler() {
        return handler;
    }

    private Handler handler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case EventCode.CTIONCONTENTSTATUS:  //链接成功开始验证
                    CommonUtils.getHandler().postDelayed(() -> {
                        blueToothClass.BindDevice();
                        blueToothClass.VerificationDevice();
                        toastUtil.showToast("已连接上,请点击手表右侧按钮进行配对");
                    }, 500);
                    break;
                case EventCode.VERIFICATION_DEVICE: //验证成功获取系统信息
                    blueToothClass.GetDeviceInfo();
                    break;
                case EventCode.CURRENT_STEP_ABOUT: //获取每分钟的计步变化
                    dataClass.filtrationStepCount(DataClass.CurrentTotalStep);
                    dataClass.filtrationPathLength(Math.round(DataClass.standardScale * DataClass.CurrentTotalStep));
                    dataClass.getStepCountWeekDb();
                    dataClass.getPathLengWeekDb();
                    break;
                case EventCode.HEART_RATE: //获取心率
                    dataManager.insertHeartRateDataInfo(new HeartRateDataInfo(UserContent.UserName, CalenderUtilsClass.getCurrentDay(true), responseHr));
                    EventBusUtil.sendEvent(new CommonEvent(EventCode.HEART_RATE));
                    break;
            }
            return true;
        }
    });

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WatchApplication.getInstance().setMainActivity(this);
        if (savedInstanceState != null) {
            showHideFragment(getTargetFragment(showFragment), getTargetFragment(hideFragment));
            hideFragment = showFragment;
        }
        openBlue();
    }

    private SupportFragment getTargetFragment(int item) {
        switch (item) {
            case Constants.TYPE_LIFE:
                return homeFragment;
            case Constants.TYPE_RIGHT:
                return personageFragment;
        }
        return homeFragment;
    }

    @Override
    protected void registerEvent(CommonEvent commonevent) {
        switch (commonevent.getCode()) {
            case EventCode.LOGIN_OUT:
                finish();
                break;
            case EventCode.LOCAL_AREA_LINKS:
                localAreaLinks();
                break;
            case EventCode.DEVICECONNECTIONCONTENT:
                blueToothClass.startScan();
                break;
            case EventCode.DEVICECONNECTION:
                BleDevice bleDevice = (BleDevice) commonevent.getObject();
                initACDb(bleDevice);
                localAreaLinks();
                break;
            case EventCode.DEVICE_BIND:
                blueToothClass.BindDevice();
                break;
            case EventCode.UN_DEVICE_BIND:
                blueToothClass.UnBindDevice();
                break;
            case EventCode.VERIFICATION_DEVICE:
                blueToothClass.VerificationDevice();
                break;
            case EventCode.SYS_DEVICE:
                blueToothClass.GetDeviceInfo();
                break;
            case EventCode.HISTORY_STEP:
                blueToothClass.GetHistoryStep();
                break;
            case EventCode.SYNC_TIME_DEVICE:
                blueToothClass.SynctimeDevice();
                break;
            case EventCode.SETTING_SIGNS_OF_DATAINFO:
                blueToothClass.SettingSignsOfDataInfo();
                break;
            case EventCode.BP_MEASURE:
                blueToothClass.BpMeasure();
                break;
            case EventCode.FOAT:
                FOTA();
                break;
            case EventCode.AF_MEASURE:
                blueToothClass.AFMeasure();
                break;
            case EventCode.HISTORY_AF:
                blueToothClass.GetHistoryAF();
                break;
            case EventCode.HRV_MEASURE:
                blueToothClass.HrvMeasure();
                break;
            case EventCode.EXERCISE:
                blueToothClass.ExerciseMeasure();
                break;
            case EventCode.BPCSTANDARD:
                blueToothClass.BpcStandard();
                break;
            case EventCode.BPCSTANDARDCLEAR:
                blueToothClass.BpcStandardClear();
                break;
            case EventCode.PULSE_CONDITION:
                List<BdDataInfo> bdDataInfos = dataManager.queryBdDataInfo(UserContent.UserName);
                if (bdDataInfos != null && bdDataInfos.size() > 0) {
                    BdDataInfo bdDataInfo = bdDataInfos.get(bdDataInfos.size() - 1);
                    NetUtils.getBody(bdDataInfo.getPvhMmHg(), bdDataInfo.getLdoMmHg());
                }
                break;
            case EventCode.PULSE_TAKING:
                netWork(commonevent.getTemp_str());
                break;
        }
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_home;
    }

    @Override
    protected void initClass() {
        dataClass = new DataClass(dataManager);
        loginWidgetClass = new LoginWidgetClass(dataManager, handler);
        loginWidgetClass.RemovePermissions();
        homeFragment = new HomeFragment();
        blueToothClass = new BlueToothClass(toastUtil, this, dataManager);
        personageFragment = new PersonageFragment();
        loadMultipleRootFragment(R.id.layout_fl, 0, homeFragment, personageFragment);
    }

    @Override
    protected void initData() {
        DataClass.CurrentTotalStep = DataClass.StepCountHourDb();
        onePixTask();
    }

    @Override
    protected void initView() {
        localBroadcastReceiver = new LocalBroadcastReceiver(this);
        IntentFilter statusFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(localBroadcastReceiver, statusFilter);
    }

    @Override
    protected void initListener() {
        group_view.setOnCheckedChangeListener(this);
        getBack();
    }

    @Override
    public void onClick(View view) {

    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
        switch (i) {
            case R.id.life:
                showFragment = Constants.TYPE_LIFE;
                break;
            case R.id.right:
                showFragment = Constants.TYPE_RIGHT;
                break;
        }
        group_view.check(i);
        showHideFragment(getTargetFragment(showFragment), getTargetFragment(hideFragment));
        hideFragment = showFragment;
    }

    //设备信息
    private void initACDb(BleDevice bleDevice) {
        AppConfigurationInfo appConfigurationInfo = dataManager.queryAppConfigurationInfo(UserContent.UserName);
        if (appConfigurationInfo != null) {
            dataManager.UpDataAppConfigurationInfo(new AppConfigurationInfo(appConfigurationInfo.getId(), UserContent.UserName, bleDevice.getMac(), bleDevice.getName(),
                    appConfigurationInfo.getObjectiveToRemind(), appConfigurationInfo.getCallReminder(), appConfigurationInfo.getSedentaryRemind()));
        } else {
            dataManager.insertAppConfigurationInfo(new AppConfigurationInfo(UserContent.UserName, bleDevice.getMac(), bleDevice.getName(), 0, 0, 0));
        }
    }

    private boolean isFirst = true;

    public void setConnect() {
        AppConfigurationInfo appConfigurationInfo = dataManager.queryAppConfigurationInfo(UserContent.UserName);
        BleManager.getInstance().scan(10000/*超时设置*/, new OnScannerListener() {
            @Override
            public void onComplete() {
                isFirst = true;
                Log.e(TAG, "onComplete");
            }

            @Override
            public void onError(Throwable throwable) {
                isFirst = true;
                Log.e(TAG, "onError");
                throwable.printStackTrace();
            }

            @Override
            public void onNext(BLEDevice bleDevice) {
                Log.e(TAG, "onNext");
                // 同一设备会被搜索到多次,请做好过滤
                if (isFirst && bleDevice != null && bleDevice.getMacAddress() != null && appConfigurationInfo != null && bleDevice.getMacAddress().equals(appConfigurationInfo.getMAC())) {
                    //isFirst = false;
                    Log.e(TAG, bleDevice.getMacAddress() + "bleDevice.getMacAddress()");
                    AppConfigurationInfo appConfigurationInfo = dataManager.queryAppConfigurationInfo(UserContent.UserName);
                    if (appConfigurationInfo != null) {
                        dataManager.UpDataAppConfigurationInfo(new AppConfigurationInfo(appConfigurationInfo.getId(), UserContent.UserName, bleDevice.getMacAddress(), bleDevice.getName(),
                                appConfigurationInfo.getObjectiveToRemind(), appConfigurationInfo.getCallReminder(), appConfigurationInfo.getSedentaryRemind()));
                    } else {
                        dataManager.insertAppConfigurationInfo(new AppConfigurationInfo(UserContent.UserName, bleDevice.getMacAddress(), bleDevice.getName(), 0, 0, 0));
                    }
                    EventBusUtil.sendEvent(new CommonEvent(EventCode.LOCAL_AREA_LINKS));
                }
            }
        });
    }

    //链接
    private void localAreaLinks() {
        AppConfigurationInfo appConfigurationInfo = dataManager.queryAppConfigurationInfo(UserContent.UserName);
        if (appConfigurationInfo != null) {   //appConfigurationInfo.getMAC()
            CommonUtils.runInThread(() -> {
                SystemClock.sleep(600);
                Looper.prepare();
                BleManager.getInstance().connect(appConfigurationInfo.getMAC(), HomeActivity.this);
                LogUtil.e(TAG, "appConfigurationInfo.getMAC(): " + appConfigurationInfo.getMAC());
                Looper.loop();
            });
        }
    }

    @Override
    public void onSuccess() {
        isFirst = false;
        DataClass.onlineStatus = true;
        handler.sendEmptyMessage(EventCode.CTIONCONTENTSTATUS);
        EventBusUtil.sendEvent(new CommonEvent(EventCode.CTIONCONTENTSTATUS, "已连接"));
        EventBusUtil.sendEvent(new CommonEvent(EventCode.PERSONAGE_UP_DATA));
        EventBusUtil.sendEvent(new CommonEvent(EventCode.FINISH_SELECT));
        EventBusUtil.sendEvent(new CommonEvent(EventCode.SYNC_TIME_DEVICE));
        EventBusUtil.sendEvent(new CommonEvent(EventCode.ADAPTER_UP_DATA));
        Log.e(TAG, "连接成功");
    }

    @Override
    public void onFailure(Throwable throwable) {
        throwable.printStackTrace();
        //localAreaLinks();
        DataClass.onlineStatus = false;
        // toastUtil.showToast("连接失败");
        EventBusUtil.sendEvent(new CommonEvent(EventCode.CTIONCONTENTSTATUS, "连接断开"));
        Log.e(TAG, "连接失败");
    }

    @Override
    public void onTimeout() {
        setConnect();
        //localAreaLinks();
        DataClass.onlineStatus = false;
        //toastUtil.showToast("连接超时");
        EventBusUtil.sendEvent(new CommonEvent(EventCode.CTIONCONTENTSTATUS, "连接断开"));
        Log.e(TAG, "连接超时");
    }

    //固件升级
    public void FOTA() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        try {
            startActivityForResult(Intent.createChooser(intent, "Select MainZhenBean File to Upload"), FILE_SELECT_CODE);
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(this, "Please install MainZhenBean File Manager.", Toast.LENGTH_SHORT).show();
        }
    }

    //握手
    public void getBack() {
        if (MessageManager.getInstance() == null) {
            return;
        }
        //命令
        MessageManager.getInstance().orderResponse(orderResponse -> {
            if (orderResponse.order.equals("D2") && orderResponse.status.equals("00")) {
                if (isUnbind) {
                    isUnbind = false;
                    BleManager.getInstance().disconnect();
                }
            }
            refreshLogView("握手回复 ： order = " + orderResponse.order + ", status = " + orderResponse.status);
        });

        //当前电量
        MessageManager.getInstance().setBatteryAndFirmwareVersionListener(batteryFirmwareVersionResponse -> {
            DataClass.Battery = String.valueOf(batteryFirmwareVersionResponse.getBattery());
            DataClass.FirmwareVersion = batteryFirmwareVersionResponse.getFirmwareVersion();
            EventBusUtil.sendEvent(new CommonEvent(EventCode.BATTERY));
            refreshLogView("Battery = " + batteryFirmwareVersionResponse.getBattery() + ", FirmwareVersion = " + batteryFirmwareVersionResponse.getFirmwareVersion());
        });

        //计步总数
        MessageManager.getInstance().setTotalStepListener(totalResponse -> {
            DataClass.TotalStep = (int) totalResponse.getTotalStep();
            DataClass.TotalCalories = (int) totalResponse.getTotalCalories();
            dataManager.insertCaloryDataInfo(new CaloryDataInfo(UserContent.UserName, CalenderUtilsClass.getCurrentDay(false), DataClass.TotalCalories));
            EventBusUtil.sendEvent(new CommonEvent(EventCode.ADAPTER_UP_DATA));
            refreshLogView("TotalStep = " + totalResponse.getTotalStep() + ", TotalCalories = " + totalResponse.getTotalCalories());
        });

        //通知监听  (移动端是否在范围类,是否穿戴松散，久坐状态，每日，锻炼开启)
        MessageManager.getInstance().setNotificationListener(notificationResponse -> {
            DataClass.Daily = notificationResponse.daily;
            DataClass.Sedentary = notificationResponse.sedentary;
            DataClass.WearingLoose = notificationResponse.wearingLoose;
            DataClass.PhoneRang = notificationResponse.phoneRang;
            refreshLogView("NotificationResponse - daily = " + notificationResponse.daily + ", sedentary = " + notificationResponse.sedentary +
                    ",wearingLoose = " + notificationResponse.wearingLoose + ", phoneRang = " + notificationResponse.phoneRang +
                    ",exercise = " + notificationResponse.exercise);
        });

        //标准值达成监听
        MessageManager.getInstance().setGoalListener(goalResponse -> refreshLogView("GoalResponse - stepCountGoal = " + goalResponse.getStepCountGoal() + ", heartRateGoal = " + goalResponse.getHeartRateGoal() +
                ",continue_Time = " + goalResponse.getContinue_Time() + ", duration = " + goalResponse.getDuration() +
                ",calorie = " + goalResponse.getCalorie()));

        //设置个人信息监听
        MessageManager.getInstance().setProfileListener(profileBean -> refreshLogView("age = " + profileBean.getAge() + ", gender = " + profileBean.getGender() +
                ",height = " + profileBean.getHeight() + ", weight = " + profileBean.getWeight() +
                ",armLength = " + profileBean.getArmLength()));

        //计步监听(每分钟心跳/1次)
        MessageManager.getInstance().setStepListener(stepResponse -> {
            DataClass.CurrentTotalStep = (int) stepResponse.getTotalStepCount();
            DataClass.CurrentTotalCalories = (int) stepResponse.getCalorie();
            handler.sendEmptyMessage(EventCode.CURRENT_STEP_ABOUT);
            handler.sendEmptyMessage(EventCode.VERIFICATION_DEVICE);
            refreshLogView("step = " + stepResponse.getTotalStepCount() + ", runStep = " + stepResponse.getRunStepCount() +
                    ",walkDuration = " + stepResponse.getTotalWalkDuration() + ", RunDuration = " + stepResponse.getTotalRunDuration() +
                    ",calorie = " + stepResponse.getCalorie());
        });

        //血压测试监听
        MessageManager.getInstance().setBpListener(bpResponse -> {
            refreshLogView("systolic = " + bpResponse.getSystolic() + ", diastolic = " + bpResponse.getDiastolic() +
                    ",hr = " + bpResponse.getHr() + ", pwtt = " + bpResponse.getPwtt());
            EventBusUtil.sendEvent(new CommonEvent(EventCode.BP_MEASURE_RETURN, bpResponse));
        });

        //获取历史记录
        MessageManager.getInstance().setHistoryEndListener(historyEndResponse -> refreshLogView("History - command = " + historyEndResponse.getCommand() + ", featureID = " + historyEndResponse.getFeatureID() +
                ",response = " + historyEndResponse.getResponse()));

        //固件升级监听
        MessageManager.getInstance().setFotaListener(new OnFotaCallbackListener() {
            @Override
            public void onCompleted() {
                refreshLogView("Fota Completed ");
            }

            @Override
            public void onError(Throwable e) {
                refreshLogView("Fota error = " + e.getMessage());
            }

            @Override
            public void onNext(Progress progress) {
                refreshLogView("固件 - Fota progress = " + progress.percent);
            }
        });

        //心率监测的API   unixTimestamp:1531124410000==responseHr:87
        MessageManager.getInstance().setHeartRateListener(hrResponse -> {
            long unixTimestamp = hrResponse.getUnixTimestamp();
            responseHr = hrResponse.getHr();
            handler.sendEmptyMessage(EventCode.HEART_RATE);
            Log.e(TAG, "unixTimestamp:" + unixTimestamp + "==" + "responseHr:" + responseHr);
        });
    }

    public void refreshLogView(String msg) {
        LogUtil.e(TAG, "refreshLogView : " + msg);
    }

    private void onePixTask() {
        onePixelReceiver = new OnePixelReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.action.SCREEN_OFF");
        intentFilter.addAction("android.intent.action.SCREEN_ON");
        intentFilter.addAction("android.intent.action.USER_PRESENT");
        registerReceiver(onePixelReceiver, intentFilter);
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        bluetoothAdapter.enable();
    }

    //脉诊网络结果插入
    private void netWork(String response) {
        if (!TextUtils.isEmpty(response)) {
            try {
                String currentDay = CalenderUtilsClass.getCurrentDay(true);
                JSONArray jsonArray = new JSONArray(response);
                int length = jsonArray.length();
                for (int i = 0; i < length; i++) {
                    JSONObject jsonObject = new JSONObject(jsonArray.getString(i));
                    dataManager.insertPulseConditionBean(new PulseConditionBean(currentDay, UserContent.UserName,
                            jsonObject.get("biaoxian").toString(),
                            jsonObject.get("jianyi").toString(),
                            jsonObject.get("maili").toString(),
                            jsonObject.get("pingji").toString(),
                            jsonObject.get("type").toString(),
                            jsonObject.get("zhengzhaung").toString(),
                            jsonObject.get("titleAdvice").toString(),
                            jsonObject.get("tupian").toString()));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onDestroy() {
        com.clj.fastble.BleManager.getInstance().disconnectAllDevice();
        com.clj.fastble.BleManager.getInstance().destroy();
        BleManager.getInstance().colse();
        BleManager.getInstance().disconnect();
        MessageManager.getInstance().unRegister();
        unregisterReceiver(onePixelReceiver);
        unregisterReceiver(localBroadcastReceiver);
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            toastUtil.showToast(getString(R.string.finish));
            exitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
        }
    }

    private void openBlue() {
        final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter.isEnabled()) {
            if (isHaiwei()) {
                bluetoothAdapter.disable();
                //CommonUtils.showToast(this, "请重启蓝牙");
                bluetoothAdapter.enable();
            }
        } else {
            CommonUtils.showToast(this, "请打开蓝牙");
            bluetoothAdapter.enable();
        }
    }

    private boolean isHaiwei() {
        String manufacturer = Build.MANUFACTURER;
        //return manufacturer.toLowerCase().equals("huawei");
        return true;
    }
}
